package com.guqj.zookeeper.lock;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.junit.Test;

public class DistributedLockTest {

	public static void main(String[] args) {
		
	}

	@Test
	public void testLock(){
		final String connect = "127.0.0.1:2181";
		ExecutorService executor = Executors.newFixedThreadPool(10);
		final int count = 10;
		final CountDownLatch latch = new CountDownLatch(count);
		for (int i = 0; i < count; i++) {
			final DistributeLock node = new DistributedReentrantLock("/locks", connect);
			executor.execute(new Runnable() {
				@Override
				public void run() {
					try {
						Thread.sleep(1000);
						// node.tryLock(); // 无阻塞获取锁
						node.lock(); // 阻塞获取锁
						// System.out.println(node.tryLock());
						Thread.sleep(1000);
						System.out.println("id: " + node.getId() + " is leader: " + node.isOwner());
					} catch (InterruptedException e) {
						e.printStackTrace();
					} finally {
						latch.countDown();
						node.unlock();
					}
				}
			});
		}

		try {
			latch.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		executor.shutdown();
	}
	
	@Test
	public void delAllNode(){
		
	}
}
